#!/usr/bin/env python3

import os
import re
import sys
from typing import List, List

STRUCTURE_FILE = "structure.txt"


def read_structure_file(filepath: str) -> List[str]:
    """读取结构文件，返回非空且非纯注释的行"""
    if not os.path.exists(filepath):
        print(f"❌ 错误：找不到结构文件 {filepath}")
        sys.exit(1)

    lines = []
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            stripped = line.strip()
            # 忽略空行或以注释开头但非内容的行（我们允许行中带注释）
            if stripped and not (stripped.startswith('#') and not re.search(r'[a-zA-Z0-9]', stripped)):
                lines.append(line.rstrip('\n'))
    
    if not lines:
        print("❌ 错误：结构文件为空")
        sys.exit(1)
    
    return lines


def extract_root_name(line: str) -> str:
    """从第一行提取根目录名，去除树形符号和注释"""
    # 去除左侧树形符号（├ └ │ ─ 空格等）和右侧注释、多余空格
    clean = re.sub(r'^[\u251c\u2514\u2502\u2500\s]+', '', line)
    clean = re.sub(r'#.*$', '', clean)
    clean = re.sub(r'\s+', ' ', clean).strip()
    return clean.rstrip('/')


def get_indent_level(line: str) -> int:
    """计算缩进层级（每4个空格为一级）"""
    # 先去除树形符号
    no_tree = re.sub(r'[\u251c\u2514\u2502\u2500]', '', line)
    # 提取开头的空白字符（包括空格和制表符）
    match = re.match(r'^\s*', no_tree)
    whitespace = match.group(0) if match else ''
    # 将制表符替换为4个空格
    expanded = whitespace.replace('\t', '    ')
    return len(expanded) // 4


def clean_line_content(line: str) -> str:
    """去除树形符号、注释、多余空格，提取名称"""
    clean = re.sub(r'^[\u251c\u2514\u2502\u2500\s]+', '', line)
    clean = re.sub(r'#.*$', '', clean)
    clean = re.sub(r'\s+', ' ', clean).strip()
    return clean


def main():
    lines = read_structure_file(STRUCTURE_FILE)
    
    # 提取根目录
    root_line = lines[0]
    root_name = extract_root_name(root_line)
    root_dir = root_name
    
    # 创建根目录
    os.makedirs(root_dir, exist_ok=True)
    print(f"📁 创建根目录: {root_dir}/")
    
    # 路径栈，保存当前层级路径
    path_stack = [root_dir]
    
    # 处理其余每一行
    for line in lines[1:]:
        clean_content = clean_line_content(line)
        if not clean_content:
            continue
        
        is_directory = clean_content.endswith('/')
        name = clean_content.rstrip('/') if is_directory else clean_content
        
        indent_level = get_indent_level(line)
        
        # 调整路径栈到当前层级（保持 0 ~ indent_level）
        path_stack = path_stack[:indent_level + 1]
        
        # 构建当前路径
        parent_path = path_stack[-1]
        current_path = os.path.join(parent_path, name)
        
        if os.path.exists(current_path):
            if is_directory and os.path.isdir(current_path):
                print(f"📁 目录已存在: {current_path}")
                path_stack.append(current_path)
            elif not is_directory and os.path.isfile(current_path):
                print(f"📄 文件已存在: {current_path}")
            else:
                print(f"❌ 冲突！路径类型不匹配: {current_path}")
            continue
        
        # 创建目录或文件
        if is_directory:
            os.makedirs(current_path, exist_ok=True)
            print(f"📁 创建目录: {current_path}")
            path_stack.append(current_path)
        else:
            # 确保父目录存在
            parent_dir = os.path.dirname(current_path)
            os.makedirs(parent_dir, exist_ok=True)
            open(current_path, 'a').close()  # touch 文件
            print(f"📄 创建文件: {current_path}")
    
    print(f"\n✅ 项目结构已成功创建在: ./{root_dir}/")


if __name__ == "__main__":
    main()
